//////////////////////////////////////////////////
// STUDENT RESEARCH PROJECT						//
// UNIVERSITY OF HAGEN 2012						//
// File:	Message.c							//
// Date:	25.08.2012							//
// Author:	Max Pejs							//
//////////////////////////////////////////////////

//////////////////
//	Includes	//
//////////////////

#include "Message.h"

#ifndef WIN32
#include "RS232Trace.h"
#endif


Message::Message()
{
	writePrt = 0;
	Write(START_OF_SEQUENCE);
}

Message::~Message(){}

void Message::Write(UInt8 c)
{
	txMessage[writePrt++] = c;
	txMessage[writePrt] = 0;
}

void Message::Write(UInt8 * str)
{
	while(*str != 0)
	{
		Write(*str);
		str++;
	}
}

void Message::WriteDataField(UInt8 * str)
{
	Write(str);
	Write(FIELD_DELIMITER);
}

void Message::TerminateMessage(void)
{
	// clear last field delimiter
	writePrt--;		

	// calculate 8 bit CRC
	UInt8 crc = Utility::calcCRC8((UInt8*)txMessage + 1);

	// get high nibble an convert to ASCII
	UInt8 highNibble = ( crc >> 4 ) & 0x0F;
	UInt8 highNibbleASCII = Utility::nibbleToAscii(highNibble);

	// get low nibble an convert to ASCII
	UInt8 lowNibble = crc & 0x0F;
	UInt8 lowNibbleASCII = Utility::nibbleToAscii(lowNibble);

	// write "end of sequence" char to the message
	Write(END_OF_SEQUENCE);

	// write crc nibble by nibble to the message
	Write(highNibbleASCII);
	Write(lowNibbleASCII);
}

void Message::SendMessage(void)
{
	TerminateMessage();
#ifdef WIN32
	// print message to console if runs in simulation
	printf("%s\n", txMessage);
#else
	// Arduino sends a message to serial port
	String msg(txMessage);
	TRACE_NL(msg);
#endif
}